/**
 * PPT模板管理器
 * 提供模板加载、占位符替换等功能
 */

import { promises as fs } from 'fs';
import { join } from 'path';
import type { PptTemplate, SlideTemplate, PlaceholderConfig } from './types.js';
import { createChildLogger, createErrorLogContext } from '../../../utils/logger.js';

export class PptTemplateManager {
  private logger = createChildLogger('PptTemplateManager');
  private templateCache = new Map<string, PptTemplate>();
  private templatesDir: string;

  constructor(templatesDir = 'templates/ppt') {
    this.templatesDir = templatesDir;
  }

  /**
   * 加载模板
   */
  async loadTemplate(templateName: string): Promise<PptTemplate> {
    // 先检查缓存
    if (this.templateCache.has(templateName)) {
      return this.templateCache.get(templateName)!;
    }

    try {
      const templatePath = join(process.cwd(), this.templatesDir, `${templateName}.json`);
      this.logger.debug('Loading PPT template', { templatePath, templateName });

      const templateContent = await fs.readFile(templatePath, 'utf-8');
      const template: PptTemplate = JSON.parse(templateContent);

      // 验证模板结构
      this.validateTemplate(template);

      // 缓存模板
      this.templateCache.set(templateName, template);

      this.logger.info('PPT template loaded successfully', { 
        templateName, 
        slidesCount: template.slides.length 
      });

      return template;
    } catch (error) {
      this.logger.error(
        'Failed to load PPT template',
        createErrorLogContext(error, { templateName })
      );
      throw new Error(`Failed to load template "${templateName}": ${error instanceof Error ? error.message : String(error)}`);
    }
  }

  /**
   * 获取可用的模板列表
   */
  async getAvailableTemplates(): Promise<string[]> {
    try {
      const templatesPath = join(process.cwd(), this.templatesDir);
      const files = await fs.readdir(templatesPath);
      return files
        .filter(file => file.endsWith('.json'))
        .map(file => file.replace('.json', ''));
    } catch (error) {
      this.logger.warn('Failed to list available templates', createErrorLogContext(error));
      return [];
    }
  }

  /**
   * 替换占位符
   */
  replacePlaceholders(text: string, data: Record<string, any>): string {
    return text.replace(/\$\{(\w+)\}/g, (match, key) => {
      const value = data[key];
      if (value === undefined || value === null) {
        this.logger.warn('Placeholder not found in data', { placeholder: key, match });
        return match; // 保持原占位符
      }
      return String(value);
    });
  }

  /**
   * 处理数组数据的占位符替换
   */
  processArrayData(template: SlideTemplate, dataArray: any[]): SlideTemplate[] {
    const processedSlides: SlideTemplate[] = [];

    for (const data of dataArray) {
      const processedSlide: SlideTemplate = {
        ...template,
        title: this.replacePlaceholders(template.title, data),
        placeholders: template.placeholders ? 
          Object.fromEntries(
            Object.entries(template.placeholders).map(([key, config]) => {
              // 这里可以根据需要处理占位符配置
              return [key, { ...config }];
            })
          ) : undefined
      };

      processedSlides.push(processedSlide);
    }

    return processedSlides;
  }

  /**
   * 验证模板结构
   */
  private validateTemplate(template: PptTemplate): void {
    if (!template.name) {
      throw new Error('Template missing required field: name');
    }

    if (!template.slides || !Array.isArray(template.slides)) {
      throw new Error('Template missing required field: slides (array)');
    }

    if (template.slides.length === 0) {
      throw new Error('Template must contain at least one slide');
    }

    // 验证每个幻灯片
    template.slides.forEach((slide, index) => {
      if (!slide.title) {
        throw new Error(`Slide ${index} missing required field: title`);
      }

      if (!slide.type) {
        throw new Error(`Slide ${index} missing required field: type`);
      }

      const validTypes = ['title', 'content', 'section', 'image', 'table'];
      if (!validTypes.includes(slide.type)) {
        throw new Error(`Slide ${index} has invalid type: ${slide.type}. Valid types: ${validTypes.join(', ')}`);
      }
    });
  }

  /**
   * 创建默认模板
   */
  static createDefaultTemplate(): PptTemplate {
    return {
      name: 'default',
      description: '默认PPT模板',
      slides: [
        {
          title: '${title}',
          type: 'title',
          layout: {
            titlePosition: 'center',
            contentAlignment: 'center'
          }
        },
        {
          title: '${sectionTitle}',
          type: 'content',
          placeholders: {
            content: {
              type: 'text',
              position: { x: '10%', y: '20%', w: '80%', h: '60%' },
              style: { fontSize: 14 }
            }
          },
          layout: {
            titlePosition: 'top',
            contentAlignment: 'left'
          }
        }
      ],
      styles: {
        backgroundColor: '#FFFFFF',
        textColor: '#333333',
        titleColor: '#2E75B6'
      }
    };
  }

  /**
   * 创建测试用例汇总模板
   */
  static createTestCaseSummaryTemplate(): PptTemplate {
    return {
      name: 'testcase-summary',
      description: '测试用例汇总PPT模板',
      slides: [
        {
          title: '测试用例汇总报告',
          type: 'title',
          layout: {
            titlePosition: 'center',
            contentAlignment: 'center'
          }
        },
        {
          title: '${module} - ${caseName}',
          type: 'content',
          placeholders: {
            level: {
              type: 'text',
              position: { x: '10%', y: '20%', w: '30%', h: '10%' },
              style: { fontSize: 12, bold: true }
            },
            precondition: {
              type: 'text',
              position: { x: '10%', y: '35%', w: '80%', h: '15%' },
              style: { fontSize: 11 }
            },
            steps: {
              type: 'list',
              position: { x: '10%', y: '55%', w: '80%', h: '25%' },
              style: { fontSize: 11 }
            },
            expected: {
              type: 'list',
              position: { x: '10%', y: '80%', w: '80%', h: '15%' },
              style: { fontSize: 11 }
            }
          },
          layout: {
            titlePosition: 'top',
            contentAlignment: 'left'
          }
        }
      ],
      styles: {
        backgroundColor: '#F8F9FA',
        textColor: '#2C3E50',
        titleColor: '#3498DB'
      }
    };
  }

  /**
   * 清除模板缓存
   */
  clearCache(): void {
    this.templateCache.clear();
    this.logger.info('Template cache cleared');
  }
}
